const express = require('express');
const bodyParser = require('body-parser')
const sha1 = require('sha1');
const request = require('request');
const app = express();

const appid = 'wxca54e54a9155264a';
const appSecret = '344f30df6b53551439add6f172b1021c';
const noncestr = 'boom';
const timestamp = 123;
let access_token, refresh_token;

app.use((req, res, next) => {
	res.header("Access-Control-Allow-Origin", "*");
	res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
	next();
})
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());


app.post('/getAccessToken', (req, res) => {
	const code = req.body.code;
	// ！如用get会报appid missing的err
	request.post({url: `https://api.weixin.qq.com/sns/oauth2/access_token`, form: {
		appid:appid,
		secret: appSecret,
		code: code,
		grant_type: 'authorization_code'
	}}, (token_err, token_res, body) =>{
		const data = JSON.parse(body);
		if(data.errcode) {
			res.send({code: 201, msg:data.errmsg});
			res.end();
		}
		else {
			access_token = data.access_token;
			refresh_token = data.refresh_token;
			res.send({code: 200, openid: data.openid});
			res.end();
			request.get(`https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${data.openid}
				&lang=zh_CN`, (user_err, user_res, user_body) => {
					console.log(user_err)
					console.log(user_body);
				})
		}
	})
})

app.listen(3000, () => console.log('server bound'))
